# -*- coding: utf-8 -*-
import frappe
from frappe.model.document import Document

class ScrapLocation(Document):
    """
    余料库位控制器
    用于管理余料库位的基本信息和状态
    """
    
    def validate(self):
        """验证余料库位数据"""
        # 检查库位代码是否重复
        if self.location_code:
            existing_location = frappe.db.exists("Scrap Location", {
                "location_code": self.location_code,
                "name": ["!=", self.name]
            })
            if existing_location:
                frappe.throw("库位代码已存在，请使用其他代码")
        
        # 检查库位名称是否重复
        if self.location_name:
            existing_name = frappe.db.exists("Scrap Location", {
                "location_name": self.location_name,
                "name": ["!=", self.name]
            })
            if existing_name:
                frappe.throw("库位名称已存在，请使用其他名称")
        
        # 检查仓库状态
        if self.warehouse:
            warehouse_status = frappe.db.get_value("Scrap Warehouse", self.warehouse, "status")
            if warehouse_status == "已取消":
                frappe.throw("无法在已取消的仓库中创建库位")
    
    def on_update(self):
        """更新余料库位时的处理"""
        # 更新关联余料信息
        self.update_related_materials()
    
    def on_trash(self):
        """删除余料库位时的处理"""
        # 检查是否有关联的余料
        materials = frappe.db.get_all("Scrap Material", 
            filters={"location": self.name})
        if materials:
            frappe.throw("无法删除该库位，存在关联的余料记录")
    
    def update_related_materials(self):
        """更新关联的余料信息"""
        # 如果库位状态变为"已停用"，则更新所有关联余料状态为"异常"
        if self.status == "已停用":
            frappe.db.sql("""
                UPDATE `tabScrap Material`
                SET status = '异常'
                WHERE location = %s AND status = '可用'
            """, self.name)
            frappe.db.commit()
    
    def get_material_count(self):
        """获取库位下的余料数量"""
        return frappe.db.count("Scrap Material", {"location": self.name})
    
    def get_available_material_count(self):
        """获取库位下的可用余料数量"""
        return frappe.db.count("Scrap Material", {"location": self.name, "status": "可用"})
    
    def generate_location_label(self):
        """生成库位标签"""
        if not self.location_label:
            # 生成默认标签格式: 仓库代码-库位代码
            if self.warehouse and self.location_code:
                warehouse_code = frappe.db.get_value("Scrap Warehouse", self.warehouse, "warehouse_code")
                self.location_label = f"{warehouse_code}-{self.location_code}"
                self.save()
                return self.location_label
        return self.location_label